﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc.Html
{
	public static class MvcHtmlTagExtensions
    {
        public static MvcHtmlTag BeginTag(this HtmlHelper htmlHelper, string tagName)
        {
            return BeginTag(htmlHelper, tagName, null);
        }

        public static MvcHtmlTag BeginTag(this HtmlHelper htmlHelper, string tagName, object htmlAttributes)
        {
            var headerCell = new TagBuilder(tagName);
            headerCell.MergeAttributes(htmlAttributes.ToDictionary());

            htmlHelper.ViewContext.Writer.Write(headerCell.ToString(TagRenderMode.StartTag));

            return new MvcHtmlTag(htmlHelper.ViewContext, headerCell.TagName);
        }

		public static MvcHtmlTag ControlGroup(this HtmlHelper htmlHelper, string htmlFieldName)
		{
			var controlGroup = new TagBuilder("div");
			controlGroup.AddCssClass("control-group");

			var modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName);

			if (htmlHelper.ViewData.ModelState.ContainsKey(modelName))
			{
				var modelState = htmlHelper.ViewData.ModelState[modelName];
				var modelErrors = (modelState == null) ? null : modelState.Errors;
				var modelError = ((modelErrors == null || modelErrors.Count == 0) ? null : modelErrors.FirstOrDefault(m => !string.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]);

				if (modelError != null)
				{
					controlGroup.AddCssClass("error");
				}
			}

			return htmlHelper.HtmlTag(controlGroup);
		}

		public static MvcHtmlTag ControlGroupFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
		{
			return ControlGroup(htmlHelper, ExpressionHelper.GetExpressionText(expression));
		}

		public static MvcHtmlTag HtmlTag(this HtmlHelper htmlHelper, TagBuilder tag)
		{
			htmlHelper.ViewContext.Writer.Write(tag.ToString(TagRenderMode.StartTag));

			return new MvcHtmlTag(htmlHelper.ViewContext, tag.TagName);
		}
	}
}